 /***************************************************************************
 *   Copyright (C) 2010 by ZhangShine , All Rights Reserved                                  
 *   zhangshine0125@gmail.com                                              
 *                                                                         
 *   This program is free software; you can redistribute it and/or modify  
 *   it under the terms of the GNU General Public License as published by  
 *   the Free Software Foundation; either version 2 of the License, or     
 *   (at your option) any later version.                                   
 *                                                                         
 *   This program is distributed in the hope that it will be useful,       
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         
 *   GNU General Public License for more details.                          
 *                                                                         
 *   You should have received a copy of the GNU General Public License     
 *   along with this program; if not, write to the                         
 *   Free Software Foundation, Inc.,                                       
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             
 ***************************************************************************/

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "account.h"
#include "sinaweibo.h"
#include "sendstatusdialog.h"
#include "sinaparserxml.h"
#include "configuration.h"
#include "showpicture.h"
#include "configuredialog.h"
#include "notifer.h"

#include <qimagereader.h>
#include <QDir>
#include <QMessageBox>
#include <QtWebKit>
#include <QtGui>

MainWindow::MainWindow(Account *account) :
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->account = account;
    this->ui->webView_Main->setPage(new QWebPage(this));
    this->dealWebkitEvent = new DealWebkitEvent(account,this);
    this->timer = new QTimer(this);// timer
    conf = Configuration::getInstance();
    ui->toolButton_Friends->setText(tr("关注数 %1").arg(account->getFriends()));
    ui->toolButton_Follower->setText(tr("粉丝数 %1").arg(account->getFollower()));
    ui->toolButton_WeiboCount->setText(tr("微博数 %1").arg(account->getWeiboCount()));;
    ui->toolButton_UserName->setText(account->getScreenName());
    moreMenu =new QMenu(this);
    about = new QAction(this);
    about->setText("关于");
    moreMenu->addAction(about);
    
    ui->toolButton_more->setMenu(moreMenu);
    ui->toolButton_more->setPopupMode(QToolButton::InstantPopup);

    QFile basicHtmlFile(":/res/homepage.html");
    if(!basicHtmlFile.open(QFile::ReadOnly))
    {
        qDebug(basicHtmlFile.errorString().toAscii());
    }
    QTextStream stream(&basicHtmlFile);
    basicHtml = stream.readAll();
    basicHtmlFile.close();
    
    this->homePageHtmlReady = false;
    this->homePageStatusReady = true;
    this->atMePageHtmlReady = false;
    this->atMePageStatusReady = false;
    this->commentPageHtmlReady = false;
    this->commentPageStatusReady = false;
    this->myWeiboPageHtmlReady = false;
    this->myWeiboPageStatusReady = false;
    this->favoritePageHtmlReady = false;
    this->favoritePageStatusReady = false;
    this->directMessagePageHtmlReady = false;
    this->directMessagePageStatusReady = false;
    this->statusUnread=0;
    this->commentsUnread=0;
    this->atMeMentionsUnread=0;
    this->directMessageUnread=0;
    this->newFollower=0;
    QObject::connect( ui->toolButton_NewWeiBo, SIGNAL(clicked()), this, SLOT(newWeiboButtonClicked()) );
    QObject::connect( ui->toolButton_HomePage, SIGNAL(clicked()), this, SLOT(homePageButtonClicked()) );
    QObject::connect( ui->toolButton_MyWeiboPage, SIGNAL(clicked()), this, SLOT(myWeiboPageButtonClicked()) );
    QObject::connect( ui->toolButton_AtMePage, SIGNAL(clicked()), this, SLOT(atMePageButtonClicked()) );
    QObject::connect( ui->toolButton_CommentPage, SIGNAL(clicked()), this, SLOT(commentPageButtonClicked()) );
    QObject::connect( ui->toolButton_FavouritePage, SIGNAL(clicked()), this, SLOT(favouritePageButtonClicked()) );
    QObject::connect( ui->toolButton_MessagePage, SIGNAL(clicked()), this, SLOT(messagePageButtonClicked()) );
    QObject::connect( about, SIGNAL(triggered()), this, SLOT(aboutQLisa()));
    QObject::connect( ui->toolButton_configure, SIGNAL(clicked()), this, SLOT(configureButtonClicked()));
    QObject::connect( ui->webView_Main->page()->mainFrame(),
                      SIGNAL(javaScriptWindowObjectCleared()),
                      this,
                      SLOT(addJavaScriptObject())
                      );
    createSystemTrayIcon();
    timer->setSingleShot(true);
    QObject::connect(timer,SIGNAL(timeout()), this, SLOT(prepare()));
    timer->start(500);//0.5s
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    hide();
    event->ignore();
}

void MainWindow::prepare()
{
    this->dealWebkitEventDisconnectThenConnect();
    //this->addJavaScriptObject();
    SinaWeibo *sina = new SinaWeibo(this->account);
    homePageButtonClicked();
    ui->toolButton_Logo->setIcon(sina->getProfileIcon(account->getProfileImageUrl()));
    delete sina;
    timer->disconnect();
    timer->stop();
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refreshStatus()));
    timer->setSingleShot(false);
    timer->start(1000*conf->getAccountConf(account->getId(), conf->updateStatusS));//90s
}

void MainWindow::preHtml()
{
    ui->webView_Main->setHtml("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />"
                                            "<center><img src=qrc:/toolButton/images/loading.gif /></center>");
    QObject::disconnect(ui->webView_Main->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
                        this, SLOT(addJavaScriptObject()));
}

void MainWindow::showPictueInWidget(QString bigUrl, QString midUrl)
{
    ShowPicture *showPicture = new ShowPicture(bigUrl, midUrl, this);
    //showPicture->setAttribute(Qt::WA_DeleteOnClose);
    showPicture->show();
}

void MainWindow::refreshStatus()
{
    timer->setInterval(1000*conf->getAccountConf(account->getId(), conf->updateStatusS));
    QWebSettings::clearIconDatabase();//clear qwebview memory cache 
    QWebSettings::clearMemoryCaches();
    
    int preStatusUnread = statusUnread; int preAtMeMentionsUnread = atMeMentionsUnread;
    int preCommentsUnread = commentsUnread; int preDirectMessageUnread = directMessageUnread;
    SinaWeibo sinaWeibo(account);
    sinaWeibo.getUnreadInfo(statusUnread, atMeMentionsUnread, commentsUnread, directMessageUnread, newFollower);
    if((statusUnread - preStatusUnread )> 0)
    {
        sinaWeibo.initHomePageStatus();
        QPixmap homePixmap(":/toolButton/images/homenew.png");
        this->updateIcon(&homePixmap, statusUnread);
        ui->toolButton_HomePage->setIcon(QIcon(homePixmap));
        this->homePageHtmlReady = false;
    }
    if((commentsUnread - preCommentsUnread )> 0)
    {
        /*
         API: http://open.t.sina.com.cn/wiki/index.php/Statuses/reset_count
         1------comments
         2------atMe
         3-------directMessage
         4-------newFollower
         */
        sinaWeibo.resetCount(1);
        sinaWeibo.initCommentPageStatus();
        QPixmap commentPixmap(":/toolButton/images/commentnew.png");
        this->updateIcon(&commentPixmap, commentsUnread);
        ui->toolButton_CommentPage->setIcon(QIcon(commentPixmap));
        this->commentPageHtmlReady = false;
    }
    if((atMeMentionsUnread - preAtMeMentionsUnread)> 0)
    {
        sinaWeibo.resetCount(2);
        sinaWeibo.initAtMePageStatus();
        QPixmap atMePixmap(":/toolButton/images/atmenew.png");
        updateIcon(&atMePixmap, atMeMentionsUnread);
        ui->toolButton_AtMePage->setIcon(QIcon(atMePixmap));
        this->atMePageHtmlReady = false;
    }
    if((directMessageUnread - preDirectMessageUnread)> 0)
    {
        sinaWeibo.resetCount(3);
        sinaWeibo.initDirectMessagePageStatus();
        //QIcon dMIcon(":/toolButton/images/messagenew.png");
        QPixmap directMessagePixmap(":/toolButton/images/messagenew.png");
        updateIcon(&directMessagePixmap, directMessageUnread);
        ui->toolButton_MessagePage->setIcon(QIcon(directMessagePixmap));
        this->directMessagePageHtmlReady = false;
    }
    this->refreshSystemTrayIconTooltip();

    QList<QLisa::NotifyObject> messageList;
    if((statusUnread - preStatusUnread)>0)
    {
        QLisa::NotifyObject obj;
        obj.type = QLisa::HomePageNumber;
        for( int i=0; i<(statusUnread-preStatusUnread); i++)
        {
            Status status = account->homePageStatus.at(i);
            obj.imageUrlPath = status.getUserProfileImageUrl();
            if(!status.getRetweetedId().isEmpty())
            {
                Status retwStatus = account->homePageRetweeted.value(status.getRetweetedId());
                obj.msg = sinaWeibo.statusToHtmlForNotifier(status, retwStatus);
             }
            else
            {
                obj.msg = sinaWeibo.statusToHtmlForNotifier(status);
            }
            messageList.append(obj);
        }
    }
    
    if((commentsUnread - preCommentsUnread)>0)
    {
        QLisa::NotifyObject obj;
        obj.type = QLisa::CommentPageNumber;
        for( int i=0; i<(commentsUnread-preCommentsUnread); i++)
        {
            Status status = account->commentPageComments.at(i);
            obj.imageUrlPath = status.getUserProfileImageUrl();
            if(!status.getRetweetedId().isEmpty())
            {
                Status retwStatus = account->commentPageRetweeted.value(status.getRetweetedId());
                obj.msg = sinaWeibo.statusToHtmlForNotifier(status, retwStatus);
             }
            else
            {
                obj.msg = sinaWeibo.statusToHtmlForNotifier(status);
            }
            messageList.append(obj);
        }
    }
    
    if((atMeMentionsUnread - preAtMeMentionsUnread)>0)
    {
        QLisa::NotifyObject obj;
        obj.type = QLisa::AtMePageNumber;
        for( int i=0; i<(atMeMentionsUnread-preAtMeMentionsUnread); i++)
        {
            Status status = account->atMePageStatus.at(i);
            obj.imageUrlPath = status.getUserProfileImageUrl();
            if(!status.getRetweetedId().isEmpty())
            {
                Status retwStatus = account->atMePageRetweeted.value(status.getRetweetedId());
                obj.msg = sinaWeibo.statusToHtmlForNotifier(status, retwStatus);
             }
            else
            {
                obj.msg = sinaWeibo.statusToHtmlForNotifier(status);
            }
            messageList.append(obj);
        }
    }
    
    if((directMessageUnread - preDirectMessageUnread)>0)
    {
        QLisa::NotifyObject obj;
        obj.type = QLisa::DirectMessagePageNumber;
        for( int i=0; i<(directMessageUnread-preDirectMessageUnread); i++)
        {
            Status status = account->directMessagePageStatus.at(i);
            obj.imageUrlPath = status.getUserProfileImageUrl();
            obj.msg = sinaWeibo.statusToHtmlForNotifier(status);
            messageList.append(obj);
        }
    }
    if(!messageList.isEmpty()&&conf->settings->value(account->getId()+"/"+conf->isNotifyCS, true).toBool())
    {
        Notifer *notifer = new Notifer();
        notifer->setAttribute(Qt::WA_DeleteOnClose);
        notifer->setNotiferContentAndShow(messageList);
    }
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    int extraHeight = height() - minimumHeight();
    ui->webView_Main->setGeometry(2, 110, 352, 531 + extraHeight);
}

void MainWindow::getOthersTimelineByScreenName(QString screenName, int page)
{
    this->preHtml();
    if(page<1)
        page = 1;
    SinaWeibo *sina = new SinaWeibo(account);
    
    QString xmlContent = sina->getUserTimelineByScreenName(screenName, 
                                                           conf->getAccountConf(account->getId(),conf->userWeiboCS), page, 0, 0);
    SinaParserXml sinaParserXml;
    QList<Status> statusList;
    QMap<QString, Status> retwStatusList;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusList);
    QString pageHtml;
    QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()==(conf->getAccountConf(account->getId(),conf->userWeiboCS)))
    {
        if(page<=1)
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",2)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName);
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",%3)>上一页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%4\",%5)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName)
                    .arg(page-1)
                    .arg(screenName)
                    .arg(page+1);
        }
    }
    else
    {
        if(page<=1)
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",2)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName);
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",%3)>上一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName)
                    .arg(page-1);
        }
    }
    contentHtml = sina->userWeiboPageStatusToHtml(statusList, retwStatusList);
    contentHtml.append(pageHtml);
    this->setWebviewHtml(basicHtml.arg(contentHtml));
    QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void MainWindow::getMoreHomePageStatus(int page, int feature)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getFriendsTimeline(0, 0, conf->getAccountConf(account->getId(), conf->homeCS),
                                                  page, 0, feature);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusList;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusList);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(),conf->homeCS)))
    {
        if(page<=1)
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreHomePageStatus(2,0)>下一页</a>"
                       "</p>";
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                     "<a href=javascript:void(0) onclick=getMoreHomePageStatus(%1,0)>上一页</a>"
                     "<a href=javascript:void(0) onclick=getMoreHomePageStatus(%2,0)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    }
    else
    {
        if(page<=1)
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                     "</p>";
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                     "<a href=javascript:void(0) onclick=getMoreHomePageStatus(%1,0)>上一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->homePageStatusToHtml(statusList, retwStatusList);
    contentHtml.append(pageHtml);
    this->setWebviewHtml(basicHtml.arg(contentHtml));
    QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void MainWindow::getMoreUserPageStatus(int page, int feature)
{
    getOthersTimelineByScreenName(account->getScreenName(),page);
}

void MainWindow::getMoreAtMePageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getMentions(0, 0, conf->getAccountConf(account->getId(), conf->atMeCS), page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusMap;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusMap);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->atMeCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(2)>下一页</a></p>";
         else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
     } else {
         if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a></p>";
         else
         {
             pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                        "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(%1)>上一页</a></p>";
             pageHtml = pageHtml.arg(page-1);
         }
     }
     contentHtml = sina->atMePageStatusToHtml(statusList, retwStatusMap);
     contentHtml.append(pageHtml);
     this->setWebviewHtml(basicHtml.arg(contentHtml));
     QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
     while(!dealWebkitEvent->isDomReady())
     {
         QApplication::processEvents();
     }
     dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
     delete sina;
}

void MainWindow::getMoreCommentsPageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getCommentTimeline(0, 0, 
                                                  conf->getAccountConf(account->getId(), conf->commentCS), page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusMap;
    sinaParserXml.parserCommentTimeline(xmlContent, statusList, retwStatusMap);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->commentCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(2)>下一页</a></p>";
        else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    } else {
        if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a></p>";
        else
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(%1)>上一页</a></p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->commentPageStatusToHtml(statusList, retwStatusMap);
    contentHtml.append(pageHtml);
    //ui->webView_Main->setHtml(basicHtml.arg(contentHtml));
    this->setWebviewHtml(basicHtml.arg(contentHtml));
    delete sina;
}

void MainWindow::getMoreFavoritePageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getFavorites(page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusMap;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusMap);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->favoriteCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(2)>下一页</a></p>";
        else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    } else {
        if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a></p>";
        else
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(%1)>上一页</a></p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->favoritePageStatusToHtml(statusList, retwStatusMap);
    contentHtml.append(pageHtml);
    this->setWebviewHtml(basicHtml.arg(contentHtml));
    QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void MainWindow::getMoreDirectMessagePageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getDirectMessage( 0, 0, 
                                                 conf->getAccountConf(account->getId(), conf->directMessageCS), page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList;
    sinaParserXml.parserDirectMessage(xmlContent, statusList);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->directMessageCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(2)>下一页</a></p>";
        else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    } else {
        if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a></p>";
        else
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(%1)>上一页</a></p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->directMessagePageStatusToHtml(statusList);
    contentHtml.append(pageHtml);
    //ui->webView_Main->setHtml(basicHtml.arg(contentHtml));
    this->setWebviewHtml(basicHtml.arg(contentHtml));
    delete sina;
}

void MainWindow::addJavaScriptObject()
{
    ui->webView_Main->page()
            ->mainFrame()
            ->addToJavaScriptWindowObject("dealWebkitEvent", this->dealWebkitEvent);
}

void MainWindow::dealWebkitEventDisconnectThenConnect()
{
    QObject::connect(dealWebkitEvent, SIGNAL(getUserTimelineByScreenNameSignal(QString, int)),
                     this, SLOT(getOthersTimelineByScreenName(QString, int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreHomePageStatusSignal(int,int)),
                     this, SLOT(getMoreHomePageStatus(int,int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreUserPageStatusSignal(int,int)),
                     this, SLOT(getMoreUserPageStatus(int,int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreAtMePageStatusSignal(int)),
                     this, SLOT(getMoreAtMePageStatus(int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreCommentsPageStatusSignal(int)),
                     this, SLOT(getMoreCommentsPageStatus(int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreFavoritePageStatusSignal(int)),
                     this, SLOT(getMoreFavoritePageStatus(int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreDirectMessagePageStatusSignal(int)),
                     this, SLOT(getMoreDirectMessagePageStatus(int)));
    QObject::connect( dealWebkitEvent, SIGNAL(showBigPicture(QString, QString)), 
                      this, SLOT(showPictueInWidget(QString,QString)));
}

void MainWindow::newWeiboButtonClicked()
{
    SendStatusDialog *sendStatusDialog = new SendStatusDialog(this->account);
    sendStatusDialog->setAttribute(Qt::WA_DeleteOnClose);
    sendStatusDialog->show();
}

void MainWindow::homePageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!homePageHtmlReady)
    {
        if(!homePageStatusReady)
        {
            sina->initHomePageStatus();
            homePageStatusReady = true;
        }
        QString pageHtml = "<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                   "<a href=javascript:void(0) onclick=getMoreHomePageStatus(2,0)>下一页</a>"
                   "</p>";
        homePageHtml = basicHtml
                       .arg(sina->homePageStatusToHtml(
                               account->homePageStatus,
                               account->homePageRetweeted)
                            );
        homePageHtml.append(pageHtml);
        homePageHtmlReady = true;
        QIcon oldIcon(":/toolButton/images/home.png");
        ui->toolButton_HomePage->setIcon(oldIcon);
        this->statusUnread=0;
        this->refreshSystemTrayIconTooltip();
    }
    this->setWebviewHtml(homePageHtml);
    QString countsInJsonFormat = sina->getStatusCountsByJson(account->homePageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void MainWindow::myWeiboPageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!myWeiboPageHtmlReady)
    {
        if(!myWeiboPageStatusReady)
        {
            sina->initUserWeiboPageStatus();
        }
        myWeiboPageHtml = basicHtml
                          .arg(sina->userWeiboPageStatusToHtml(
                                  account->userWeiboPageStatus, 
                                  account->userWeiboPageRetweeted)
                               );
        myWeiboPageHtml.append( "<p><a href=javascript:void(0) onclick=getMoreUserPageStatus(1,0)>首页</a>"
                                 "<a href=javascript:void(0) onclick=getMoreUserPageStatus(2,0)>下一页</a>"
                                 "</p>");
    }
    this->setWebviewHtml(myWeiboPageHtml);
    QString countsInJsonFormat = sina->getStatusCountsByJson(account->userWeiboPageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void MainWindow::atMePageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!atMePageHtmlReady)
    {
        if(!atMePageStatusReady)
        {
            sina->initAtMePageStatus();
            atMePageStatusReady = true;
        }
        atMePageHtml = basicHtml
                       .arg(sina->atMePageStatusToHtml(
                               account->atMePageStatus, 
                               account->atMePageRetweeted)
                            );
        if(account->atMePageStatus.length()>=conf->getAccountConf(account->getId(), conf->atMeCS))
            atMePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                                "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(2)>下一页</a></p>");
        else
            atMePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a></p>");
        atMePageHtmlReady = true;
        QIcon atMeOldIcon(":/toolButton/images/atme.png");
        ui->toolButton_AtMePage->setIcon(atMeOldIcon);
        this->atMeMentionsUnread = 0;
        this->refreshSystemTrayIconTooltip();
    }
    this->setWebviewHtml(atMePageHtml);
    QString countsInJsonFormat = sina->getStatusCountsByJson(account->atMePageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void MainWindow::commentPageButtonClicked()
{
    this->preHtml();
    if(!commentPageHtmlReady)
    {
        SinaWeibo *sina = new SinaWeibo(account);
        if(!commentPageStatusReady)
        {
            sina->initCommentPageStatus();
            commentPageStatusReady = true;
        }
        commentPageHtml = basicHtml
                          .arg(sina->commentPageStatusToHtml(
                                  account->commentPageComments, 
                                  account->commentPageRetweeted)
                               );
        if(account->commentPageComments.length()>=conf->getAccountConf(account->getId(), conf->commentCS))
            commentPageHtml.append("<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                                   "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(2)>下一页</a></p>");
        else
            commentPageHtml
                    .append("<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a></p>");
        commentPageHtmlReady = true;
        delete sina;
        QIcon commentOldIcon(":/toolButton/images/comment.png");
        ui->toolButton_CommentPage->setIcon(commentOldIcon);
        this->commentsUnread = 0;
        this->refreshSystemTrayIconTooltip();
    }
    //ui->webView_Main->setHtml(commentPageHtml);
    this->setWebviewHtml(commentPageHtml);
}

void MainWindow::favouritePageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!favoritePageHtmlReady)
    {
        if(!favoritePageStatusReady)
        {
            sina->initFavoritePageStatus();
        }
        favoritePageHtml = basicHtml
                           .arg(sina->favoritePageStatusToHtml(
                                   account->favoritesPageStatus, 
                                   account->favoritesPageRetweeted)
                                );
        if(account->favoritesPageStatus.length()>=conf->getAccountConf(account->getId(), conf->favoriteCS))
            favoritePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                                    "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(2)>下一页</a></p>");
        else
            favoritePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a></p>");
    }
    this->setWebviewHtml(favoritePageHtml);
    QString countsInJsonFormat = sina->getStatusCountsByJson(account->favoritesPageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void MainWindow::messagePageButtonClicked()
{
    this->preHtml();
    if(!directMessagePageHtmlReady)
    {
        SinaWeibo *sina = new SinaWeibo(account);
        if(!directMessagePageStatusReady)
        {
            sina->initDirectMessagePageStatus();
            directMessagePageStatusReady = true;
        }
        directMessagePageHtml = basicHtml
                                .arg(sina->directMessagePageStatusToHtml(
                                        account->directMessagePageStatus));
        if(account->directMessagePageStatus.length()>=conf->getAccountConf(account->getId(), conf->directMessageCS))
            directMessagePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                                    "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(2)>下一页</a></p>");
        else
            directMessagePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a></p>");
        this->directMessagePageHtmlReady = true;
        delete sina;
        QIcon messageOldIcon(":/toolButton/images/message.png");
        ui->toolButton_MessagePage->setIcon(messageOldIcon);
        this->directMessageUnread = 0;
        this->refreshSystemTrayIconTooltip();
    }
    
    //ui->webView_Main->setHtml(directMessagePageHtml);
    this->setWebviewHtml(directMessagePageHtml);
}

void MainWindow::configureButtonClicked()
{
    ConfigureDialog *confDialog = new ConfigureDialog(account->getId(), this);
    confDialog->setAttribute(Qt::WA_DeleteOnClose);
    confDialog->show();
}

void MainWindow::systemTrayIconAction(QSystemTrayIcon::ActivationReason reason)
{
    if(reason==QSystemTrayIcon::DoubleClick)
        this->showNormal();
    if(reason==QSystemTrayIcon::Trigger)
        this->showNormal();
}

void MainWindow::createSystemTrayIcon()
{
    this->systemTrayIcon = new QSystemTrayIcon(this);
    this->restoreAction = new QAction(tr("打开主面板"), this);
    QObject::connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
    QObject::connect(systemTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), 
                     this, SLOT(systemTrayIconAction(QSystemTrayIcon::ActivationReason)));
    this->quitAction = new QAction(tr("退出"), this);
    QObject::connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    this->systemTrayMenu = new QMenu(this);
    this->systemTrayMenu->addAction(restoreAction);
    this->systemTrayMenu->addAction(quitAction);
    this->systemTrayIcon->setContextMenu(this->systemTrayMenu);
    this->systemTrayIcon->setIcon(QIcon(":/logo/images/qlisa.png"));
    this->systemTrayIcon->setVisible(true);
}

void MainWindow::refreshSystemTrayIconTooltip()
{
    QString msg = "未读微博%1条,\n新评论%2条,\n新私信%3条,\n有%4条微博提到我";
    msg = msg
          .arg(statusUnread)
          .arg(commentsUnread)
          .arg(directMessageUnread)
      //    .arg(newFollower)
          .arg(atMeMentionsUnread);
    //systemTrayIcon->showMessage("Lisa", msg);
    systemTrayIcon->setToolTip(msg);
}

void MainWindow::aboutQLisa()
{
    AboutDialog *aboutDialog = new AboutDialog();
    aboutDialog->setAttribute(Qt::WA_DeleteOnClose);
    aboutDialog->show();
}

void MainWindow::setWebviewHtml(QString html)
{

    QWebPage *oldPage = ui->webView_Main->page();
//    delete oldPage;
//    QWebPage *newPage = new QWebPage(ui->webView_Main);
//    newPage->mainFrame()->setHtml(html);
//    ui->webView_Main->setPage(newPage);
//    this->addJavaScriptObject();

    QWebPage *newPage = new QWebPage(this);
    ui->webView_Main->setPage(newPage);
    oldPage->deleteLater();
    QObject::connect( ui->webView_Main->page()->mainFrame(),
                      SIGNAL(javaScriptWindowObjectCleared()),
                      this,
                      SLOT(addJavaScriptObject())
                      );
    DealWebkitEvent *old = this->dealWebkitEvent;
    this->dealWebkitEvent = new DealWebkitEvent(account, this);
    old->deleteLater();
    
    this->dealWebkitEventDisconnectThenConnect();
    this->addJavaScriptObject();    
    this->dealWebkitEvent->setDomReady(false);
    ui->webView_Main->setHtml(html);
}

void MainWindow::updateIcon(QPixmap *pixmap, int unreadCount)
{
    QPainter painter(pixmap);
    painter.setPen(Qt::red);
    QFont font("Arial", 10, 10);
    font.setBold(true);
    painter.setFont(font);
    painter.drawText(0, 0, 32, 32, Qt::AlignCenter, QString::number(unreadCount), 0);
}
